package com.xiaozhengkeji.servlet.dao.user;

import com.xiaozhengkeji.servlet.servlet.user.UserRegClass;
import com.xiaozhengkeji.servlet.tools.INITool;

import java.io.UnsupportedEncodingException;
import java.security.spec.PSSParameterSpec;
import java.sql.*;

public class UserReg {
    private String pathClass = this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
    private String pathsql;
    private String Sql_JDBC_URL;
    private String Sql_JDBC_USER;
    private String Sql_JDBC_PASSWORD;

    public UserReg() {
        {
            try {
                pathsql = java.net.URLDecoder.decode(pathClass + "com\\xiaozhengkeji\\servlet\\config\\sqlConfig.ini", "UTF-8");
                this.Sql_JDBC_URL = INITool.getConfig("Sql_JDBC_URL", pathsql);
                this.Sql_JDBC_USER = INITool.getConfig("Sql_JDBC_USER", pathsql);
                this.Sql_JDBC_PASSWORD = INITool.getConfig("Sql_JDBC_PASSWORD", pathsql);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 注册用户
     */
    public UserRegClass regUser(String name, String password, String email) {
        UserRegClass urc = new UserRegClass();
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            Connection c = DriverManager.getConnection(this.Sql_JDBC_URL, this.Sql_JDBC_USER, this.Sql_JDBC_PASSWORD);
            PreparedStatement ps = null;
            String sql = "SELECT user_name FROM servletUser where user_name=?";
            ps = c.prepareStatement(sql);
            ps.setString(1, name);
            ResultSet rs = null;
            rs = ps.executeQuery();
            while (rs.next()) {
                urc.setCode("400");
                urc.setMessage("注册失败!已经存在本账号!");
                return urc;
            }
            rs.close();
            rs = null;
            ps.close();
            ps = null;
            String sql0 = "INSERT INTO servletUser (id, user_name, password, form, email) VALUES (null, ?, ?, ?, ?)";
            ps = c.prepareStatement(sql0);
            ps.setString(1, name);
            ps.setString(2, password);
            ps.setString(3, "default");
            ps.setString(4, email);
            int row = ps.executeUpdate();
            if (row > 0) {
                urc.setMessage("注册成功!");
                urc.setCode("1");
                return urc;
            } else {
                urc.setMessage("注册失败!");
                urc.setCode("-1");
                return urc;
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return urc;
    }
}
